package com.dayuanit.dy16.ebook.ebookweb.controller;

import com.dayuanit.dy16.ebook.ebookweb.dto.ResponseDTO;
import com.dayuanit.dy16.ebook.ebookweb.service.ICardService;
import com.dayuanit.dy16.ebook.ebookweb.service.IRedisService;
import com.dayuanit.dy16.ebook.ebookweb.vo.SettlementRequestVO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class CardController extends BaseController {

    @Autowired
    private ICardService cardService;

    @Autowired
    private IRedisService redisService;

    @RequestMapping("/card/addCard")
    public ResponseDTO addCard(long commoId, int buyNum) {
        cardService.addCard(commoId, buyNum, getUserId());
        return ResponseDTO.success();
    }

    @RequestMapping("/cart/loadCart")
    public ResponseDTO loadCart() {
        return ResponseDTO.success(cardService.loadCart(getUserId()));
    }

    /**
     *  私人协议：购物车ID-商品ID-购买数量$购物车ID-商品ID-购买数量
     * @return
     */
    @RequestMapping("/cart/settlementOne")
    public ResponseDTO settlementOne(String settlementInfo) {
        String[] settlements = settlementInfo.split("\\$");
        List<SettlementRequestVO> setttlementList = new ArrayList<>(settlements.length);
        for (String settlement : settlements) {
            String[] cartInfo = settlement.split("-");
            long cartId = Long.valueOf(cartInfo[0]);
            long commodityId = Long.valueOf(cartInfo[1]);
            int buyNum = Integer.valueOf(cartInfo[2]);

            setttlementList.add(new SettlementRequestVO(cartId, commodityId, buyNum));
        }

        setttlementList.forEach(System.out::println);

        return ResponseDTO.success(cardService.loadCart(getUserId()));
    }

    /**
     * 方案二 推荐
     * 使用json格式传输复杂参数
     *
     * 通过@RequestBody注解，将前端传的json数据反序列化成Java对象
     * @param settlements
     * @return
     */
    @RequestMapping("/cart/settlementTwo")
    public ResponseDTO settlementTwo(@RequestBody List<SettlementRequestVO> settlements) {
        settlements.forEach(System.out::println);
        redisService.saveSettleInfo(getUserId(), settlements);
        return ResponseDTO.success();
    }
}
